package com.enjoyor.health.HGPT.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.enjoyor.health.HGPT.core.config.Constant;
import com.enjoyor.health.HGPT.core.config.ParamConfig;
import com.enjoyor.health.HGPT.core.dto.DialogDto;
import com.enjoyor.health.HGPT.core.entity.DialogContent;
import com.enjoyor.health.HGPT.core.entity.DialogRecord;
import com.enjoyor.health.HGPT.core.entity.ReportRecord;
import com.enjoyor.health.HGPT.core.entity.UserInfoMiniapp;
import com.enjoyor.health.HGPT.core.service.IDialogContentService;
import com.enjoyor.health.HGPT.core.service.IDialogRecordService;
import com.enjoyor.health.HGPT.core.service.IReportRecordService;
import com.enjoyor.health.HGPT.core.service.IUserInfoMiniappService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author Zhu Min
 * @date 2023/10/20 11:08
 */
@Slf4j
@Service
public class BizConversationService {

    @Autowired
    private IDialogContentService dialogContentService;
    @Autowired
    private IUserInfoMiniappService userInfoMiniappService;
    @Autowired
    private IDialogRecordService dialogRecordService;
    @Autowired
    private IReportRecordService reportRecordService;
    @Autowired
    private ParamConfig paramConfig;

    public List<DialogContent> getDialogContentById(String dialogId){
        return dialogContentService.getDialogContentById(dialogId);
    }

    public void getDbTalk(String uuid, String openId){
        UserInfoMiniapp userInfoMiniapp = userInfoMiniappService.getUserInfoMiniappByOpenId(openId);
        if (userInfoMiniapp != null && StringUtils.isNotBlank(userInfoMiniapp.getUserId())){
            LocalDateTime now = LocalDateTime.now();
            DialogRecord dialogRecord = new DialogRecord();
            dialogRecord.setId(uuid);
            dialogRecord.setUserId(userInfoMiniapp.getUserId());
            dialogRecord.setName(Constant.DIALOG_NAME);
            dialogRecord.setState(1);
            dialogRecord.setBeginTime(now);
            dialogRecord.setEndTime(now);
            dialogRecord.setUpdateTime(now);
            dialogRecord.setStorageTime(now);
            dialogRecordService.save(dialogRecord);
            log.info("conversation_app插入成功：{}", uuid);
        }else {
            log.info("conversation_app数据插入失败，当前open_id无user_id {}", openId);
        }
        //TODO 原代码返回固定的disease，后面的就不查询了

    }

    public JSONArray dialogList(String openId){
        List<DialogDto> dialogDtoList = dialogRecordService.getDialogRecordByOpenId(openId);
        JSONArray array = new JSONArray();
        for (DialogDto dialogDto : dialogDtoList) {
            JSONObject result = new JSONObject();
            result.put("name", dialogDto.getName());
            result.put("dialogId", dialogDto.getDialogId());
            array.add(result);
        }
        return array;
    }

    public void updateDialogEvaluation(String evaluation, String evaluationDetail, String comment, String dialogId, String number){
        dialogContentService.updateDialogContent(evaluation, evaluationDetail, comment, dialogId, number);
    }

    public int updateDialogName(String name, String dialogId){
        return dialogRecordService.updateDialogRecordName(name, dialogId);
    }

    public int updateDialogState(int state, String dialogId){
        return dialogRecordService.updateDialogRecordState(state, dialogId);
    }

    public JSONObject getAnswerFromAI(String question, String openId, String dialogId){
        String title = "";
        String content = "";
        JSONArray moreQuestion = new JSONArray();
        int statement = 0;
        String url = null;
        String time = "";
        Integer number = null;

        if (StringUtils.isNotBlank(question)){
            if (question.contains("原发性高血压的危害（图文）")){
                content = "原发性高血压的危害（图文）";
                url = "../../packPageA/information/information?newsId=a0c26fbbe4744a2b944e4bc9e1d77e5a";
            }else if (question.contains("原发性高血压的危害（视频）")){
                content = "原发性高血压的危害（视频）";
                url = "../../packPageA/information/information?newsId=117ab91e1644467c955dc7eadb3f74f8";
            }else if (question.contains("血管粥样硬化的形成（图文）")){
                content = "血管粥样硬化的形成（图文）";
                url = "../../packPageA/information/information?newsId=cbad0c0c925de72465047282e92802ee";
            }else if (question.contains("脑梗多半都是“拖”出来的（图文）")){
                content = "脑梗多半都是“拖”出来的（图文）";
                url = "../../packPageA/information/information?newsId=376618d19064fa1333158d9bedae8677";
            }else if (question.contains("抑郁测评")){
                content = "抑郁测评";
                url = "../../packPageA/selfTesting/selfTesting?selftestId=1232&openId=" + openId;
            }else if (question.contains("焦虑测评")){
                content = "焦虑测评";
                url = "../../packPageA/selfTesting/selfTesting?selftestId=1233&openId=" + openId;
            }else if (question.contains("神经衰弱测评")){
                content = "神经衰弱测评";
                url = "../../packPageA/selfTesting/selfTesting?selftestId=1234&openId=" + openId;
            }else if (question.contains("体检报告") || question.contains("体检") ||question.contains("报告") ||question.contains("健康报告") ||question.contains("健康") ){
                //获取version
                String version = "";
                //我的报告只去找type1的
                ReportRecord reportRecord = reportRecordService.getLatestVersionByType(openId, 1);
                if (reportRecord != null) {
                    version = reportRecord.getVersion();
                    if (reportRecord.getReportType() == 1){
                        content = "我的健康报告";
                        url = "../../packPageA/examinationReport/examinationReport_shanghai?openId="+openId+"&version="+version;
                    }else if (reportRecord.getReportType() == 2){
                        content = "我的健康报告";
                        url = "../../packPageA/examinationReport/examinationReport?openId="+openId+"&version="+version;
                    }else {
                        //不知道什么类型
                        content = "我的健康报告";
                        url = "../../packPageA/examinationReport/examinationReport?openId="+openId+"&version="+version;

                    }
                }else {
                    content = "还未有健康报告生成，请先预约";
                    url = "";
//                    moreQuestion.add("原发性高血压的危害（图文）");
//                    moreQuestion.add("血管粥样硬化的形成（图文）");
                }

            }else if (question.contains("展会体验包")){
                //
                ReportRecord reportRecord = reportRecordService.getLatestVersionByType(openId, 2);
                if (reportRecord == null || reportRecord.getVersion() == null){
                    content = "还未有健康报告生成，请先预约";
                    url = "";
//                    moreQuestion.add("原发性高血压的危害（图文）");
//                    moreQuestion.add("血管粥样硬化的形成（图文）");
                }else {
                    content = "展会体验包";
                    url = "../../packPageA/examinationReport/examinationReport?openId="+openId+"&version="+reportRecord.getVersion();
                }
            } else {
                /**
                 * {
                 * "message": "success",
                 * "result": {
                 * "content": "基于血压升高的程度，高血压又可分为1型和2型。\n1型高血压，也称恶性高血压，是指青年发病，急进性进展，除外慢性疾病外，有遗传因素、吸烟、饮酒等不良嗜好，有明确高血压家族史，或在长期熬夜、失眠等情况，因治疗不彻底而引发脑动脉供血不足等临床综合征。\n2型高血压，又称慢性逐渐性高血压，是指青年发病，渐呈进行性进展，一般与糖尿病、慢性肝炎、肾脏疾病等慢性疾病并存，也称变性高血压，多数患者在积极治疗原发性高血压的同时，亦发生糖尿病，如果患者已有糖尿病，应尽可能避免糖尿病加重，一般糖尿病需给予低糖饮食。", //gpt回答的内容
                 * "moreQuestion": [
                 * "高血压的预防",
                 * "原发性高血压的危害（图文）",
                 * "原发性高血压的危害（视频）"
                 * ], //猜你想问
                 * "title": "" //回答的标题
                 * },
                 * "statusCode": 200
                 * }
                 */
                try {
                    String aiUrl = paramConfig.getAiUrl() + "?dialogId=" + dialogId + "&question=" + question + "&openId=" + openId;
                    HttpResponse response = HttpRequest.get(aiUrl).timeout(30 * 1000).execute();
                    JSONObject responseBody = JSONObject.parseObject(response.body());
                    if (responseBody != null){
                        title = responseBody.getJSONObject("result").getString("title");
                        content = responseBody.getJSONObject("result").getString("content");
                        url = responseBody.getJSONObject("result").getString("url");
                        moreQuestion = responseBody.getJSONObject("result").getJSONArray("moreQuestion");
                        //AI接口目前没返回statement
                        statement = 1;
                    }
                }catch (Exception e){
                    log.error("请求AI问答接口出错",e);
                }
            }
        }

        //保存问答记录
        JSONObject contentJson = new JSONObject();
        contentJson.put(question, content);
        JSONObject numberTimeJson = getTimeNumberOfConversation(dialogId, contentJson.toJSONString(), question, content, statement, title, url);
        LocalDateTime newTime = numberTimeJson.getObject("newTime", LocalDateTime.class);
        if (newTime != null){
            time = newTime.format(DateTimeFormatter.ofPattern(Constant.DATE_TIME_FORMAT));
        }
        number = numberTimeJson.getInteger("number");
        //
        dialogRecordService.updateDialogRecordName(question, dialogId);
        if (moreQuestion == null){
            moreQuestion = new JSONArray();
        }
        if ("原发性高血压".equals(question)){
            moreQuestion.add("高血压的预防");
        }else if (question.contains("原发性高血压")){
            moreQuestion.add("原发性高血压的危害（图文）");
            moreQuestion.add("原发性高血压的危害（视频）");
        }

        JSONObject result = new JSONObject();
        result.put("time", time);
        result.put("title", title);
        result.put("content", content);
        result.put("statement", statement);
        result.put("url", url);
        result.put("number", number);
        result.put("moreQuestion", moreQuestion);
        return result;
    }

    private JSONObject getTimeNumberOfConversation(String dialogId, String content, String question, String showContent,
                                                   Integer showStatement, String title, String url){
        List<DialogContent> dialogContentList = dialogContentService.getDialogContentById(dialogId);
        int number = 1;
        LocalDateTime showTime = null;
        LocalDateTime newTime = null;
        if (dialogContentList != null){
            number = dialogContentList.size() + 1;
        }
        if (number > 1){
            LocalDateTime oldTime = dialogContentService.getLatestDialogById(dialogId).getTime();
            Duration timeDifference = Duration.between(oldTime, LocalDateTime.now());
            if (timeDifference.getSeconds()/60 >3){
                newTime = LocalDateTime.now();
                showTime = newTime;
            }else {
                showTime = null;
            }
        }

        DialogContent dialogContent = new DialogContent();
        dialogContent.setId(IdUtil.simpleUUID());
        dialogContent.setDialogId(dialogId);
        dialogContent.setContent(content);
        dialogContent.setTime(LocalDateTime.now());
        dialogContent.setQuestion(question);
        dialogContent.setShowContent(showContent);
        dialogContent.setShowStatement(showStatement);
        dialogContent.setShowTime(showTime);
        dialogContent.setShowTitle(title);
        dialogContent.setShowUrl(url);
        dialogContent.setNumber(number);
        dialogContent.setStorageTime(LocalDateTime.now());
        dialogContent.setUpdateTime(LocalDateTime.now());
        dialogContentService.save(dialogContent);

        JSONObject ret = new JSONObject();
        ret.put("newTime", newTime);
        ret.put("number", number);
        return ret;
    }


}
